const http = require("http");
const fs = require("fs");
const url = require("url");
const qs = require("querystring");
const re = require("request");
http.createServer((req, res) => {
    if (req.url !== "/favicon.ico") {
      if(req.url.indexOf("/suggest") != -1){
        apirequest(req, res);
      }else
      if(req.url.indexOf("/api") != -1) {
        message(req, res);
      } else {
        file(req, res);
      }
    }
  }).listen(3000);
  function apirequest(req, res){
    let reUrl = url.parse(req.url,true).path;
    reUrl="https:/"+reUrl;
    re(reUrl, (err, response, body)=>{
      if(!err && response.statusCode == 200){
        var data = body;
        res.write(data);
        res.end();
      } 
    })
  }
function message(req, res) {
  let str = "";
  req.on("data", (c) => {
    str += c;
  });
  req.on("end", (c) => {
    let dataObj;
    console.log(str)
    if(str){
        dataObj=qs.parse(str);
    }else{
        dataObj=url.parse(req.url, true).query;
    }
    if(dataObj.type==="login"){
        login(req,res,dataObj);
    }else if(dataObj.type==="register"){
        register(req,res,dataObj);
    }
  });
}
function login(req,res,dataObj){
    fs.readFile("./user.json",(err,data)=>{
    if(err) {
      return console.log(err);
    }
    data=JSON.parse(data.toString("utf-8"))
    let i=0;
    const flag = data.some((val,idx)=>{
        i = idx;
        return val.username === dataObj.username;
    })
    if(flag){
        if(data[i].password === dataObj.password){
            res.write(JSON.stringify({code:2,title:"登录成功",data:dataObj.username}));
            res.end();
            return;
        }else{
            res.write(JSON.stringify({code:1,title:"密码不对",data:"NOTDATA"}))
            res.end();
            return;
        }
    }else{
        res.write(JSON.stringify({code:0,title:"用户名不存在",data:"NOTDATA"}))
        res.end();
        return;
    }
    res.end();
  })
}
function register(req,res,dataObj){
  fs.readFile("./user.json",(err,data)=>{
    if(err) {
      return console.log(err);
    }
    data=JSON.parse(data.toString("utf-8"))
    for(var i=0;i<data.length;i++){
      if(dataObj.username===data[i].username){
        res.write('{"mes":"重复用户名","code":1,"data":"NODATA"}');
        res.end();
        return;
      }
    }
    data.push({'username':dataObj.username,'password':dataObj.password})
    fs.writeFile("./user.json", JSON.stringify(data), (err)=> {
          if(err) {
              return console.log(err);
          }
          res.write(JSON.stringify({mes:"注册成功！",code:0,data:{username:dataObj.username}}));
          res.end();
      });
  })
}

function file(req, res) {
  const now=url.parse(req.url,true).pathname;
  fs.readFile("./www" + now, (err, data) => {
    if (err) {
      res.write("404");
    } else {
      res.write(data);
    }
    res.end();
  });
}
